#!/bin/bash
#author: kavinyao@gmail.com

echo "Welcome to command line stack prompt"
echo "Enter help for help"

_stack_str=""

function help() {
    echo "Command usage:"
    echo "push elem1 [elem2 ...] - add elements to top"
    echo "pop [n] - pop the top n elements, n is default to 1"
    echo "quit - quit the program"
}

function push() {
    if [ "$1" = "push" ]; then
        echo "please provide at least one argument!"
    else
        for elem in $@; do
            elem=${elem##*-} # remove reserved character
            _stack_str=$elem-$_stack_str
            echo "successfully pushed $elem"
        done
    fi
}

function pop() {
    if [ $(echo $1 | egrep "^[0-9]+$") ]; then
        times=$1
    else
        times=1
    fi

    while [ -n "$_stack_str" -a $times -gt 0 ]; do 
        elem=${_stack_str%%-*}
        echo "$elem is popped"
        _stack_str=${_stack_str#*-}
        times=$(($times-1))
    done
}

while true; do
    echo -n "> "
    read option

    case ${option%% *} in
        "repr")
            echo $_stack_str
            ;;
        "help")
            help
            ;;
        "push")
            param=${option#push }
            push $param
            ;;
        "pop")
            param=${option#pop }
            pop $param
            ;;
        "quit")
            exit 0
            ;;
        *)
            echo "unrecognized command. try enter help"
            ;;
    esac
done

